import { Component, ViewChild } from '@angular/core';
import { Nav, Platform, Events, App, ToastController,
    LoadingController, AlertController } from 'ionic-angular';

import { MyBaseApp } from "./BaseAppComponent";
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { AppGlobal } from '../providers/appGlobal';
import { UserProvider } from '../providers/service/user';
import { LoginPage } from '../pages/login/login';
import { HomePage } from '../pages/home/home';
import { DevicePage } from '../pages/device/device';
// import { ListPage } from '../pages/list/list';
import { UserPage } from '../pages/user/user';
// import { AlarmPage } from '../pages/alarm/alarm';
import { BadPage } from '../pages/bad/bad';
import { MsgPage } from '../pages/msg/msg';
import { TabsPage } from '../pages/tabs/tabs';

import { JpushService } from '../providers/jpushService';
import { DEFINE } from '../providers/Constants';
import { Clipboard } from '@ionic-native/clipboard';

@Component({
    templateUrl: 'app.html'
})
export class MyApp extends MyBaseApp {
    @ViewChild(Nav) nav: Nav;

    rootPage:any = TabsPage;

    // rootPage: any;

    pages: Array<{ title: string, component: any, icon: string }>;

    logOutpage: Object;

    backButtonPressed: boolean = false;

    //版本更新的判断相关参数
    version = '';
    c_alert;
    c_toast;

    constructor(public platform: Platform,
        public statusBar: StatusBar,
        public splashScreen: SplashScreen,
        public alertCtrl: AlertController,
        public toastCtrl: ToastController,
        public app: App,
        public userProvider: UserProvider,
        public loadingCtrl: LoadingController,
        public jpushService: JpushService,
        public toast: ToastController,
        public clipboard: Clipboard,
        public event: Events) {

        super(platform, app, toast);

        this.initializeApp();

        // used for an example of ngFor and navigation
        this.pages = [
            { title: '首页', component: HomePage, icon: 'ios-home' },
            { title: '设备列表', component: DevicePage, icon: 'ios-nuclear' },
            { title: '故障列表', component: BadPage, icon: 'ios-flash' },
            // { title: '报警列表', component: AlarmPage, icon: 'ios-flash' },
            { title: '消息', component: MsgPage, icon: 'ios-megaphone' },
            // { title: '测试消息', component: ListPage, icon: 'ios-cog' },
            { title: '个人中心', component: UserPage, icon: 'ios-contact' }
        ];

        this.logOutpage = { title: '注销', component: LoginPage, icon: 'ios-power' }

        //监听LOGOUT，跳转到登录界面
        this.event.subscribe('LOGOUT', () => {
            // alert('LOGOUT');
            AppGlobal.getInstance().clearTokenAndUser();
            this.nav.setRoot(LoginPage);
            // this.rootPage = LoginPage;
        })

        //接收到消息后 跳转到消息列表页面
        this.event.subscribe('GET_MESSAGE', () => {
            this.nav.push(MsgPage);
        })

        this.checkVersion();
    }

    initializeApp() {
        this.platform.ready().then(() => {
            // Okay, so the platform is ready and our plugins are available.
            // Here you can do any higher level native things you might need.
            this.statusBar.styleDefault();
            this.splashScreen.hide();
            try{
                this.jpushService.init().then(res=>{
                    this.jpushService.openListenEvent();
                },err=>{
                    
                });
            }catch(e){
            }
            //判断用户是否登录过，如果存在token，就直接进入页面
            if (AppGlobal.getInstance().getToken()) {
                // this.rootPage = HomePage;
                this.rootPage = TabsPage;
                //如果不存在用户信息，则异步获取用户信息
                let loading = this.loadingCtrl.create({
                    content: '正在初始化'
                });
                loading.present();
                if (!AppGlobal.getInstance().getUserInfo()) {
                    this.userProvider.getUserInfoByToken().then(res => {
                        loading.dismiss();
                    }, err => {
                        loading.dismiss();
                    });
                }
            } else {
                this.rootPage = LoginPage;
            }
        });
    }

    openPage(page) {
        // console.log(this.nav.getActive());
        // console.log(this.nav.getViews());
        // Reset the content nav to have just this page
        // we wouldn't want the back button to show in this scenario
        this.nav.setRoot(page.component);

    }

    //清除用户相关信息
    clearData() {
        AppGlobal.getInstance().clearTokenAndUser();
    }

    //实现父类 退出APP
    exitApp() {
        this.platform.exitApp();
    }

    checkVersion() {

        if (this.platform.is('ios')) {
            this.version = DEFINE.ios_version;
        }
        else if (this.platform.is('android')) {
            this.version = DEFINE.android_version;
        }else{
            this.version = DEFINE.android_version;
        }

        if (this.platform.is('ios')) {
            this.userProvider.getAppVersion({ 'platform': 2 }).then((res:any) => {
                if (this.transVersion(this.version ,res.version)) {
                    this.c_alert = this.alertCtrl.create({
                        title: '温馨提示',
                        subTitle: '有新版本啦！请前往app store中，更新应用',
                        buttons: ['确认']
                    });
                    this.c_alert.present();
                } else {
                    // this.c_toast = this.toastCtrl.create({
                    //     message: '当前为最新版本',
                    //     duration: 3000
                    // });
                    // this.c_toast.present();
                }
            }, err => {
            })

        }
        else if (this.platform.is('android')) {
            this.userProvider.getAppVersion({ 'platform': 1 }).then((res:any) => {
                if (this.transVersion(this.version ,res.version)) {
                    this.clipboard.copy(DEFINE.baseURL+'/getFile/'+res.url);
                    this.c_alert = this.alertCtrl.create({
                        title: '温馨提示',
                        subTitle: '有新版本啦！链接确认后自动复制，并在浏览器中粘贴下载',
                        buttons: ['确认并复制']
                    });
                    this.c_alert.present();
                } else {
                    // this.c_toast = this.toastCtrl.create({
                    //     message: '当前为最新版本',
                    //     duration: 3000
                    // });
                    // this.c_toast.present();
                }
            }, err => {
            })

        } else {
            // let toast = this.toastCtrl.create({
            //     message: '抱歉，无法识别手机操作系统',
            //     duration: 3000
            // });
            // toast.present();
            // loading.dismiss();
        }

    }


    /**
     *
     * @param v1 当前版本
     * @param v2 最新版本
     */
    transVersion(v1,v2){

        try{
            var arr1 = v1.split('.');
            var arr2 = v2.split('.');
            if(parseInt(arr2[0]) > parseInt(arr1[0])){
                return true;
            }
            if(parseInt(arr2[1]) > parseInt(arr1[1])){
                return true;
            }
            if(parseInt(arr2[2]) > parseInt(arr1[2])){
                return true;
            }
            return false;
        }catch(e){
            return false;
        }

    }
}
